<template>
  <div v-if="authStore.isAuthenticated" class="form-body">
    <div class="background-image"></div>
    <div class="form-container">
      <a-form :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }" @finish="handleSubmit">

        <!-- SRU编号 -->
        <a-form-item label="SRU编号" name="sruNumber" :rules="[{ required: true, message: '请输入SRU编号!' }]">
          <a-input v-model:value="formState.sruNumber" placeholder="自动获取SRU编号" :disabled="true" />
        </a-form-item>

        <!-- 地址 -->
        <a-form-item label="地址" name="address" :rules="[{ required: true, message: '请选择地址!' }]">
          <a-select v-model:value="formState.address" placeholder="请选择苏格兰地区" show-search option-filter-prop="label">
            <a-select-option v-for="area in scottishAreas" :key="area.value" :value="area.value" :label="area.label">
              {{ area.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- 出生日期 -->
        <a-form-item label="出生日期" name="birthDate" :rules="[{ required: true, message: '请选择出生日期!' }]">
          <a-date-picker v-model:value="formState.birthDate" value-format="YYYY-MM-DD" style="width: 100%" />
        </a-form-item>

        <!-- 电话号码 -->
        <a-form-item label="电话号码" name="phoneNumber" :rules="[{ required: true, message: '请输入电话号码!' }]">
          <a-input v-model:value="formState.phoneNumber" placeholder="请输入电话号码" />
        </a-form-item>

        <!-- 手机号码 -->
        <a-form-item label="手机号码" name="mobileNumber" :rules="[{ required: true, message: '请输入手机号码!' }]">
          <a-input v-model:value="formState.mobileNumber" placeholder="请输入手机号码" />
        </a-form-item>

        <!-- 邮政编码 -->
        <a-form-item label="邮政编码" name="zipCode" :rules="[{ required: true, message: '请输入邮政编码!' }]">
          <a-input v-model:value="formState.zipCode" placeholder="将根据地区自动填充" :disabled="true" />
        </a-form-item>

        <!-- 邮箱 -->
        <a-form-item label="邮箱" name="email" :rules="[{ required: true, type: 'email', message: '请输入有效的邮箱地址!' }]">
          <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
        </a-form-item>

        <!-- 提交按钮 -->
        <a-form-item :wrapper-col="{ offset: 6, span: 14 }">
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
  <a-alert v-else class="no-data" type="warning" show-icon>
    <template #message>
      您必须登录/注册才可以申请非玩家会员
    </template>
    <template #description>
      将在 {{ countdown }} 秒后跳转到登录页面...
    </template>
  </a-alert>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import axios from "../axios";
import { useAuthStore } from '../store/auth';
import { generateSRUNumberFromToken } from '../utils/tokenUtils'; // 引入工具函数

const countdown = ref(5); // 倒计时初始值
const authStore = useAuthStore();
const router = useRouter();

// 定义表单状态
const formState = reactive({
  sruNumber: '',
  address: '',
  birthDate: '',
  phoneNumber: '',
  mobileNumber: '',
  zipCode: '',
  email: '',
});

// 表单提交处理
const handleSubmit = async () => {
  try {
    const response = await axios.post('/non_members', formState);
    message.success('非会员成员申请成功！');
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    // console.log(axiosError.response);
    if (axiosError.response?.data?.code === 401) {
      message.error(axiosError.response.data.message || '用户名或密码错误。');
    } else if (axiosError.response?.data?.code === 400) {
      message.error(axiosError.response.data.message || '验证码错误，请重试。');
    } else if (axiosError.response?.data?.code === 409) {
      message.error(axiosError.response.data.message || '已申请会员，请重试。');
    }else {
      message.error('提交失败，请检查输入或联系管理员！');
    }
    
  }
};
// 监听未登录状态，启动倒计时
watch(() => authStore.isAuthenticated, (isAuthenticated) => {
  if (!isAuthenticated) {
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(timer);
        router.push({ name: 'Auth' });
      }
    }, 1000);
  }
}, { immediate: true }); // 立即执行

// 监听地址变化
watch(() => formState.address, (newVal) => {
  const selectedArea = scottishAreas.find(area => area.value === newVal);
  if (selectedArea) {
    formState.zipCode = selectedArea.postcode;
    // 可以添加更精确的示例：formState.zipCode = `${selectedArea.postcode}1 1${Math.floor(Math.random()*9)}Z`;
  }
});
// 苏格兰行政区列表参考
const scottishAreas = reactive([
  { value: 'aberdeen-city', label: 'Aberdeen City', postcode: 'AB10-AB25' },
  { value: 'edinburgh', label: 'City of Edinburgh', postcode: 'EH1-EH17' },
  { value: 'glasgow', label: 'Glasgow City', postcode: 'G1-G80' },
  { value: 'stirling', label: 'Stirling', postcode: 'FK7-FK9' },
  // 其他地区补充完整邮编前缀...
]);

onMounted(async () => {
  try {
    // 仅在已认证且token存在时执行赋值
    if (authStore.isAuthenticated && authStore.token) {
      // 使用工具函数生成 SRU 编号
      formState.sruNumber = generateSRUNumberFromToken(authStore.token);
    } else {
      // 处理未登录或token缺失的情况（如清空SRU编号）
      formState.sruNumber = '';
    }
  } catch (e) {
    message.error('用户信息加载失败，请重试');
  }
});

</script>


<style scoped>
/* 页面整体布局 */
.form-body {
  position: relative; /* 相对定位，作为子元素的参考点 */
  display: flex;
  flex-direction: row; /* 水平布局 */
  align-items: stretch; /* 子元素高度拉伸 */
  min-height: 60vh; /* 确保页面占满整个视口高度 */
  margin: 0 auto; /* 左右居中 */
  padding: 0 40px; /* 左右留出空间 */
  max-width: 1800px; /* 限制最大宽度 */
}

/* 左侧背景图片 */
.background-image {
  position: relative; /* 相对定位 */
  width: 50%; /* 固定宽度 */
  height: 800px; /* 固定高度 */
  background: url('../static/form.png') no-repeat left center; /* 图片靠左对齐 */
  background-size: auto 100%; /* 高度填满，宽度自动调整 */
}

/* 右侧表单容器 */
.form-container {
  position: absolute; /* 绝对定位，覆盖在背景图片上 */
  top: 50%; /* 垂直居中 */
  right: 40px; /* 距离右侧留出空间 */
  transform: translateY(-50%); /* 垂直居中调整 */
  width: 800px; /* 固定宽度 */
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.9); /* 半透明背景 */
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 10; /* 确保表单容器在背景图片之上 */
}
.no-data {
  text-align: center;
  font-size: 1.2em;
  color: #999;
}

/* 响应式设计：小屏幕设备 */
@media (max-width: 768px) {
  .form-body {
    flex-direction: column; /* 垂直布局 */
  }

  .background-image {
    height: 200px; /* 固定高度 */
    flex: none; /* 不再拉伸 */
  }

  .form-container {
    max-width: 100%; /* 占据全宽 */
    margin: 20px auto; /* 上下间距 */
  }
}
</style>
